package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Classname RedisIdWoker
 * @Description ID唯一性算法
 * @Date 2022/5/23 20:01
 * @Created by 86182
 */
@Component
public class RedisIdWoker {

    private static final long BEGIN_TEMPTIMEST = 1640995200L;
    private static final int COUNT = 32;


    private StringRedisTemplate stringRedisTemplate;


    public RedisIdWoker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
//        1、生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeTemp = nowSecond - BEGIN_TEMPTIMEST;
//        2、生成序列号
//        2.1 根据时间获取当前时间日期
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
//        2.2存放redis自增长
        Long key = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + format);
        return timeTemp << 32 | key;
    }


}
